package com.steven.im.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.MotionEvent;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.igexin.sdk.PushManager;
import com.steven.im.App;
import com.steven.im.R;
import com.steven.im.base.BaseActivity;
import com.steven.im.base.Constant;
import com.steven.im.entity.BaseEntity;
import com.steven.im.entity.BaseEventEntity;
import com.steven.im.entity.MainTabEntity;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.ui.fragment.IMAccountFragment;
import com.steven.im.ui.fragment.IMChatMsgFragment;
import com.steven.im.ui.fragment.IMContactsFragment;
import com.steven.im.utils.SystemUtils;
import com.steven.im.utils.UserUtils;
import com.steven.im.widget.CenterDialog;
import com.steven.im.widget.GetuiIntentService;
import com.steven.im.widget.GetuiPushService;


import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

import retrofit2.Response;

public class MainActivity extends BaseActivity {

    long lastClickTime = 0;//判断是否快速点击

    private CommonTabLayout mTabLayout;
    ArrayList<Fragment> mFragments = new ArrayList<>();
    private int currentTab = 0;
//    private MyIUiListener myIUiListener;//QQ分享回调接口

    @Override
    public void setTitleBarColor() {
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initData() {
        String[] mTitles = {getString(R.string.msg), getString(R.string.contact), getString(R.string.my)};
        int[] mIconUnSelectIds = {
                R.drawable.icon_message_unselected, R.drawable.icon_contact_unselected,
                R.drawable.icon_mine_unselected};
        int[] mIconSelectIds = {
                R.drawable.icon_message_selected, R.drawable.icon_contact_selected,
                R.drawable.icon_mine_selected};
        //tab的标题、选中图标、未选中图标
        ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
        //设置tab的标题、选中图标、未选中图标
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new MainTabEntity(mTitles[i], mIconSelectIds[i], mIconUnSelectIds[i]));
        }
        //初始化数据
        mFragments.add(new IMChatMsgFragment());
        mFragments.add(new IMContactsFragment());
        mFragments.add(new IMAccountFragment());
        //给tab设置数据和关联的fragment
        mTabLayout.setTabData(mTabEntities, this, R.id.fl_change, mFragments);

        mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (!UserUtils.checkLogin() && position != 2) {//用户未登录且不在个人页，记录当前页
                    currentTab = position;
                }
            }

            @Override
            public void onTabReselect(int position) {
                if (!UserUtils.checkLogin() && position != 2) {//用户未登录且不在个人页，记录当前页
                    currentTab = position;
                }
            }
        });
        checkVersion();
    }

    //检测系统版本
    private void checkVersion() {
        Task.getApiService().checkVersion().enqueue(new MyCallback<BaseEntity>(MainActivity.this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                if ("0".equals(response.body().getCode())) {
                    String description = response.body().getResult().getString("description");
                    String linkUrl = response.body().getResult().getString("link");
                    String type = response.body().getResult().getString("type");
                    String version_romate = response.body().getResult().getString("version");
                    String version_local = SystemUtils.getLocalVersionName(App.getContext());
                    if (SystemUtils.compareVersion(version_local, version_romate) < 0) {
                        new CenterDialog(R.layout.updatapk_dialog, MainActivity.this)
                                .showUpdatePrompt(getApplicationContext(), description, type, linkUrl);
                    }
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    @Override
    public void initView() {
        //初始化组件
        mTabLayout = findViewById(R.id.tl);

        //初始化个推服务
        PushManager.getInstance().initialize(this.getApplicationContext(), GetuiPushService.class);
        // com.getui.demo.DemoIntentService 为第三方自定义的推送服务事件接收类
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), GetuiIntentService.class);

//        初始化QQ分享
//        myIUiListener = new MyIUiListener();
    }

    @Override
    public void setListen() {
    }

    /**
     * 处理快速点击造成的重复生成界面影响
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isFastDoubleClick()) {
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onPause() {
        super.onPause();
        String str = "{\"isStop\": true}";
        JSONObject object = JSONObject.parseObject(str);
        BaseEventEntity baseEventEntity = new BaseEventEntity();
        baseEventEntity.setTitle("home");
        baseEventEntity.setResult(object);
        EventBus.getDefault().post(baseEventEntity);
    }

    @Override
    protected void onResume() {
        super.onResume();
        String str = "{\"isStop\": false}";
        JSONObject object = JSONObject.parseObject(str);
        BaseEventEntity baseEventEntity = new BaseEventEntity();
        baseEventEntity.setTitle("home");
        baseEventEntity.setResult(object);
        EventBus.getDefault().post(baseEventEntity);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        int tab = intent.getIntExtra("tab", 0);
        switch (tab) {
            case 0:
            case 3:
                mTabLayout.setCurrentTab(tab);
                break;
            case 1:
                String categoryId = intent.getStringExtra("actionUrl");
                toCategory(categoryId);
                break;
        }
    }

    /**
     * 判断是否快速点击(时间间隔在300ms以内，就算快速点击)
     *
     * @return
     */
    private boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        lastClickTime = time;
        return timeD <= 300;
    }

    /**
     * 获取底部控件
     *
     * @return
     */
    public CommonTabLayout getTabLayout() {
        return mTabLayout;
    }

    /**
     * 获取当前页
     */
    public int getCurrentTab() {
        return currentTab;
    }

    /**
     * 跳转到分类页面
     *
     * @param categoryId
     */
    private void toCategory(String categoryId) {
        mTabLayout.setCurrentTab(1);
        Bundle bundle = new Bundle();
        bundle.putString("categoryId", categoryId);
        if (mFragments.get(1) != null) {
            mFragments.get(1).setArguments(bundle);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);
        if (requestCode == Constant.QRCode) {
            if (result.getContents() != null) {
                startActivity(new Intent(this, IMUserInfoActivity.class));
            } else if (!Constant.isPhoto) {
                Toast.makeText(this, "scan error!", Toast.LENGTH_SHORT).show();
            }
        }
    }

}

